import java.io.IOException;
import java.net.*;
import java.nio.channels.ClosedSelectorException;

public class UdpClient {
    private DatagramSocket socket;
    private int serverPort;
    private String serverIP;
    private static final int TimeOut=1000;

    public UdpClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP=serverIP;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        long[] RTT_array = new long[10];
        int n = 0;
        for (int i = 0; i < 10; i++) {
            //1.build datagram
            String request = "ping";
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIP), serverPort);

            //2.send request
            long startTime = System.currentTimeMillis();
            socket.send(requestPacket);

            //3.receive response
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            long endTime = System.currentTimeMillis();
            RTT_array[i] = endTime - startTime;
            if (RTT_array[i] <= 1000) {
                System.out.println("RTT:" + RTT_array[i] + "ms");
            } else {
                System.out.println("请求超时");
                n++;
            }

        }

        quicksort(RTT_array,0,RTT_array.length-1);
        long sum=0;
        for (int i = 0; i < RTT_array.length; i++) {
            sum+=RTT_array[i];
        }
        double mean=sum*1.0/RTT_array.length;
        System.out.println("最小时间："+RTT_array[0]+"ms,最大时间："+RTT_array[RTT_array.length-1]+
                "ms,平均时间:"+mean+"ms");
        double lose=n/10.;
        System.out.println("丢包率:"+String.format("%.2f%%",lose));


    }
    void quicksort(long [] array,int low,int high){
        if(low>=high) return;
        int i = low, j = high;
        //选base应避免选到极值，找三个值的中位数作为base
        double base = array[low];
        while(i<j){
//必须先排右边,因为停止的位置要被换到开头，必须小于base
            while(array[j]>=base && i<j){
                j--;
            }
            while(array[i]<=base && i<j){
                i++;
            }
            swap(array,i,j);
        }
        swap(array,low,j);
        quicksort(array,low,j-1);
        quicksort(array,j+1,high);
    }
    void swap(long [] array ,int i , int j){
        long key=array[i];
        array[i]=array[j];
        array[j]=key;
    }

    public static void main(String[] args) throws IOException {
        UdpClient client=new UdpClient("127.0.0.1",12521);
        client.start();
    }
}
